<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Messageuser extends Model
{
    protected $table = 'messageuser';
    public $timestamps = false;
    protected $guarded = [
        'address', 'room', 'area', 'phone', 'created_at', 'updated_at', 'deleted_at'
    ];

    public function getData($search = [], $page = 1, $length = 20){
        $messageuserList = array();
        $messageuserList['pageData'] = array();
        $date = date('Y-m-d H:i:s', time());

        $sql = \DB::table($this->table.' as m')
            ->select('u.nick_name','m.address','m.room','m.area','m.phone','m.created_at','m.updated_at','m.id')
            ->leftjoin('users as u','m.user_id','=','u.id')
            ->whereNull('m.deleted_at');

        if(isset($search['address'])){
            $sql->where('m.address', 'like', '%'.$search['address'].'%');
        }
        if(isset($search['phone'])){
            $sql->where('m.phone', 'like', '%'.$search['phone'].'%');
        }

        $messageuserList['pageData']['count']     = $sql->count();
        $messageuserList['pageData']['lastPage']  = ceil($messageuserList['pageData']['count'] / $length);

        $messageuserList['list'] = $sql->orderBy('m.updated_at', 'desc')
            ->skip(($page-1) * $length)->take($length)
            ->get();

        return $messageuserList;
    }

    public function saveData($data){
        return \DB::table($this->table)->insert($data);
    }

    public function setData($id,$data){
        return \DB::table($this->table)->where('id',$id)->update($data);
    }

    public function delData($id,$data){
        return \DB::table($this->table)->where('id',$id)->update($data);
    }

}